package com.ruoyi.system.mongo.Impl;

import com.mongodb.client.result.DeleteResult;
import com.ruoyi.system.domain.mongodb.Users;
import com.ruoyi.system.domain.mongodb.Works;
import com.ruoyi.system.mongo.WorksDao;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author HP
 * @Date 2021/3/3
 * @Description TODO
 */
@Repository
public class WorksDaoImpl implements WorksDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Works> queryWorks() {
        List<Works> works = mongoTemplate.findAll(Works.class);
        return works;
    }

    /**
     * 根据作品id查询学生id
     * @param work_id
     * @return
     */
    @Override
    public String queryWorksByWorkId(String work_id) {
        Query query = new Query(Criteria.where("_id").is(work_id));
        Works work = mongoTemplate.findOne(query, Works.class);
        return work.getUser();
    }

    @Override
    public Long deleteWorksById(String work_id) {
        Query query = new Query(Criteria.where("_id").is(work_id));
        DeleteResult remove = mongoTemplate.remove(query, Works.class);
        return remove.getDeletedCount();
    }

    @Override
    public Works saveWorks(Works works) {
        return mongoTemplate.insert(works);
    }


    public Works queryWorksById(String work_id) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(work_id)));
        Works work = mongoTemplate.findOne(query, Works.class);
        return work;
    }
}
